//
//  ColorAnimationView.swift
//  animations
//
//  Created by Ekaterina on 16.01.2023.
//

import SwiftUI

struct ColorAnimationView: View {
    @State var selectedColor = Color.red
    @State var firstColor = Color(UIColor(hexCode: "#FF000F"))
    @State var secondColor = Color(UIColor(hexCode: "#FFF500"))
    
    @State var isSecondColor = false
    @State var duration = 1.0;
    
    let minDuration = 0.1
    let maxDuration = 2.0
    
    var body: some View {
        VStack(spacing: 24) {
            Rectangle()
                .modifier(AnimatableColorModifier(isSecondColor: isSecondColor, firstColor: firstColor, secondColor: secondColor))
            
            VStack(spacing: 16) {
                HStack {
                    TitledColorPicker(title: "First Color:", color: $firstColor)
                    Spacer()
                    TitledColorPicker(title: "Second Color:", color: $secondColor)
                }
                Divider()
                
                ValueSlider(title: "Duration", minValue: minDuration, maxValue: maxDuration, value: $duration)
                
                PlayButton {
                    withAnimation(.easeInOut(duration: duration)) {
                        isSecondColor.toggle()
                    }
                }
            }
            .padding(24)
        }
        .navigationTitle("Color Animation")
        .navigationBarTitleDisplayMode(.inline)
    }
}

struct AnimatableColorModifier: Animatable, ViewModifier {
    private var progress = 0.0
    private var firstColor: Color
    private var secondColor: Color
    
    var animatableData: Double {
        get { return progress }
        set {
            progress = newValue
        }
    }
    
    init(isSecondColor: Bool, firstColor: Color, secondColor: Color) {
        self.progress = isSecondColor ? 1.0 : 0.0
        self.firstColor = firstColor
        self.secondColor = secondColor
    }
    
    func body(content: Content) -> some View {
        let firstC = UIColor(firstColor).cgColor.components ?? [0, 0, 0]
        let secondC = UIColor(secondColor).cgColor.components ?? [0, 0, 0]
        
        let red = firstC[0] + (secondC[0] - firstC[0]) * progress
        let green = firstC[1] + (secondC[1] - firstC[1]) * progress
        let blue = firstC[2] + (secondC[2] - firstC[2]) * progress
        
        return Rectangle().fill(Color(red: red, green: green, blue: blue))
    }
}

struct ColorAnimationView_Previews: PreviewProvider {
    static var previews: some View {
        ColorAnimationView()
    }
}
